{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 🧠 Week 2 Assignment – Deep Research Assistant with Pushover Notifications\n",
    "\n",
    "# Author: Bharat Puri\n",
    "# Objective: Combine OpenAI Agents SDK, WebSearchTool, and Pushover alerts into a deployable Gradio app.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install git+https://github.com/openai/openai-agents-python.git"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# -------------------------------------------------------------\n",
    "# 1. Imports\n",
    "# -------------------------------------------------------------\n",
    "from agents import Agent, WebSearchTool, Runner, trace\n",
    "from dotenv import load_dotenv\n",
    "from IPython.display import Markdown, display\n",
    "import gradio as gr\n",
    "import requests\n",
    "import asyncio\n",
    "import os"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# -------------------------------------------------------------\n",
    "# 2. Load environment variables\n",
    "# -------------------------------------------------------------\n",
    "load_dotenv(override=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# -------------------------------------------------------------\n",
    "# 3. Define Agent Instructions and Setup\n",
    "# -------------------------------------------------------------\n",
    "INSTRUCTIONS = (\n",
    "    \"You are a research assistant. Given a search term, search the web for that term and \"\n",
    "    \"produce a concise summary of the results. The summary must be 2-3 paragraphs and under 300 words. \"\n",
    "    \"Capture the key insights clearly, without fluff or filler. Output only the summary text.\"\n",
    ")\n",
    "\n",
    "# Create the Deep Research agent\n",
    "search_agent = Agent(\n",
    "    name=\"DeepResearcher\",\n",
    "    instructions=INSTRUCTIONS,\n",
    "    model=\"gpt-4o-mini\",\n",
    "    tools=[WebSearchTool()]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# -------------------------------------------------------------\n",
    "# 4. Define Pushover Notification Function\n",
    "# -------------------------------------------------------------\n",
    "def send_pushover_notification(title: str, message: str):\n",
    "    \"\"\"\n",
    "    Sends a push notification using the Pushover API.\n",
    "    \"\"\"\n",
    "    token = os.environ.get(\"PUSHOVER_TOKEN\")\n",
    "    user = os.environ.get(\"PUSHOVER_USER\")\n",
    "    if not token or not user:\n",
    "        print(\"⚠️ Pushover credentials not found in .env\")\n",
    "        return \"Pushover not configured\"\n",
    "\n",
    "    url = \"https://api.pushover.net/1/messages.json\"\n",
    "    data = {\n",
    "        \"token\": token,\n",
    "        \"user\": user,\n",
    "        \"title\": title,\n",
    "        \"message\": message,\n",
    "    }\n",
    "    try:\n",
    "        response = requests.post(url, data=data, timeout=10)\n",
    "        if response.status_code == 200:\n",
    "            print(\"✅ Pushover notification sent successfully.\")\n",
    "            return \"Notification sent!\"\n",
    "        else:\n",
    "            print(\"⚠️ Failed to send Pushover notification:\", response.text)\n",
    "            return f\"Error: {response.text}\"\n",
    "    except Exception as e:\n",
    "        print(\"Error sending Pushover:\", e)\n",
    "        return f\"Exception: {e}\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# -------------------------------------------------------------\n",
    "# 5. Define Async Research Logic\n",
    "# -------------------------------------------------------------\n",
    "async def run_research(query: str) -> str:\n",
    "    \"\"\"\n",
    "    Runs the Deep Research agent on a given query and returns a formatted summary.\n",
    "    \"\"\"\n",
    "    if not query.strip():\n",
    "        return \"Please provide a valid search query.\"\n",
    "\n",
    "    print(f\"🔍 Running research for topic: {query}\")\n",
    "    with trace(\"Deep Research Session\"):\n",
    "        result = await Runner.run(search_agent, query)\n",
    "\n",
    "    summary = result.final_output\n",
    "    print(\"✅ Research completed.\")\n",
    "\n",
    "    # Run the Pushover notification in a separate thread (non-blocking)\n",
    "    loop = asyncio.get_event_loop()\n",
    "    loop.run_in_executor(None, send_pushover_notification, \"Deep Research Completed\", f\"Topic: {query}\")\n",
    "\n",
    "    return summary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# -------------------------------------------------------------\n",
    "# 6. Gradio Interface\n",
    "# -------------------------------------------------------------\n",
    "async def gradio_interface(query):\n",
    "    \"\"\"\n",
    "    Wrapper for Gradio async interface.\n",
    "    \"\"\"\n",
    "    summary = await run_research(query)\n",
    "    return summary\n",
    "\n",
    "\n",
    "iface = gr.Interface(\n",
    "    fn=gradio_interface,\n",
    "    inputs=gr.Textbox(\n",
    "        label=\"Enter research topic\",\n",
    "        placeholder=\"e.g., AI Agent Frameworks 2025\",\n",
    "        lines=2,\n",
    "    ),\n",
    "    outputs=gr.Markdown(label=\"Research Summary\"),\n",
    "    title=\"🔎 Deep Research Assistant with Pushover\",\n",
    "    description=(\n",
    "        \"An AI Agent that searches the web and summarizes insights for you.\\n\\n\"\n",
    "        \"💡 You'll also get a **Pushover notification** when your research is ready!\"\n",
    "    ),\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# -------------------------------------------------------------\n",
    "# 7. Launch App\n",
    "# -------------------------------------------------------------\n",
    "iface.launch()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
